package com.glasses.business.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.glasses.business.R;
import com.glasses.business.adapter.TagAdapter;
import com.glasses.business.appliction.MyApplication;
import com.glasses.business.entity.Product0;
import com.glasses.business.entity.ProductDetail;
import com.glasses.business.entity.SelectItem;
import com.glasses.business.event.BussEvent;
import com.glasses.business.fmanager.BaseFragment;
import com.glasses.business.http.NetUtils;
import com.glasses.business.inter.OnItemClick;
import com.glasses.business.utils.ObservableScrollView;
import com.glasses.business.utils.Tools;

import net.neiquan.applibrary.flowtag.FlowTagLayout;
import net.neiquan.applibrary.flowtag.OnTagSelectListener;
import net.neiquan.applibrary.wight.ProgressWebView;
import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Author：邓勇军
 * English Name：Deng,The Sky Fucker!
 * Email：dandycoder@126.com
 * Date：2017/3/10
 * Version：1.0
 */

public class GlassDetailFragment extends BaseFragment implements ObservableScrollView.ScrollViewListener {
    @InjectView(R.id.glassScrollView)
    ObservableScrollView glassScrollView;
    @InjectView(R.id.ly_back)
    LinearLayout lyBack;
    @InjectView(R.id.back_img)
    ImageView backImg;
    @InjectView(R.id.title_tv)
    TextView titleTv;
    @InjectView(R.id.head_view)
    RelativeLayout headView;
    @InjectView(R.id.glassImg)
    SimpleDraweeView glassImg;
    @InjectView(R.id.glassDetail)
    TextView glassDetail;
    @InjectView(R.id.glassPrice)
    TextView glassPrice;
    @InjectView(R.id.glassTransp)
    TextView glassTransp;
    @InjectView(R.id.glassPlace)
    TextView glassPlace;
    @InjectView(R.id.glassWeb)
    ProgressWebView glassWeb;
    @InjectView(R.id.glassMoney)
    TextView glassMoney;
    @InjectView(R.id.glassTime)
    TextView glassTime;
    @InjectView(R.id.glassOrder)
    TextView glassOrder;
    private int id;
    private int type;
    private ProductDetail productDetail;
    private SelectItem.ValueBean valueBean;

    @Override
    public int getRootViewId() {
        return R.layout.fragment_glass_pair_detail;
    }

    @Override
    public void setViews() {
//        glassImg.setImageURI("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1489129557&di=3dac99356aa888601a14ea84483a8503&src=http://pic45.nipic.com/20140730/12005913_135124217000_2.jpg");
        titleTv.setVisibility(View.GONE);
        glassWeb.getSettings().setJavaScriptEnabled(true);
//        glassWeb.loadUrl("http://www.loho88.com/?utm_source=bdss2&utm_medium=cpc&utm_campaign=1%2E12&utm_term=%E7%AB%9E%E7%A7%80%5F%5F%E6%A0%87%E9%A2%98");
        glassScrollView.setScrollViewListener(this);
    }

    @Override
    public void initData() {
        if (getArguments() != null) {
            id = getArguments().getInt("id");
            type = getArguments().getInt("type");
        }
        loadDatas();
    }

    private void loadDatas() {
        Tools.showDialog(getActivity());
        NetUtils.getInstance().productDetail(id, type, new NetCallBack() {

            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                productDetail = ((ProductDetail) model.getModel());
                glassImg.setImageURI(productDetail.getPicture());
                glassWeb.loadUrl(productDetail.getUrl());
                glassDetail.setText(productDetail.getName());
                glassPlace.setText(productDetail.getAddress());
                glassPrice.setText("￥" + productDetail.getPrice());
                glassMoney.setText("价格;￥"+productDetail.getPrice());
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
            }
        }, ProductDetail.class);
    }

    @Override
    public boolean mainTabShow() {
        return false;
    }

    @OnClick({R.id.ly_back, R.id.glassOrder})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ly_back:
                MyApplication.getInstance().manager.onBackPressed();
                break;
            case R.id.glassOrder:
                switch (type) {
                    case 0:
                        showPopupWindow();
                        break;
                    case 1:
                        ToastUtil.shortShowToast("该镜片加入订单成功!");
                        BussEvent event = new BussEvent(BussEvent.Product1);
                        event.setMessage(productDetail);
                        EventBus.getDefault().post(event);
                        MyApplication.getInstance().manager.onBackPressed();
                        break;
                }
                break;
        }
    }

    private List<SelectItem.ValueBean> datas = new ArrayList<SelectItem.ValueBean>();

    private void showPopupWindow() {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.glass_choose_pop, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.5f; //0.0-1.0
        getActivity().getWindow().setAttributes(lp);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
//                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
//                lp.alpha = 1.0f; //0.0-1.0
//                getActivity().getWindow().setAttributes(lp);
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.wheel_bg));
        popupWindow.setAnimationStyle(net.neiquan.applibrary.R.style.Animation_Bottom);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1.0f; //0.0-1.0
                getActivity().getWindow().setAttributes(lp);
            }
        });

        final FlowTagLayout popFlowLayout = ((FlowTagLayout) contentView.findViewById(R.id.popFlowLayout));
        contentView.findViewById(R.id.popSure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AppLog.e("=========valueBean========" + valueBean);
                if (valueBean == null) {
                    ToastUtil.shortShowToast("请先选择颜色...");
                } else {
                    popupWindow.dismiss();
                    ToastUtil.shortShowToast("该镜架加入订单成功!");
                    BussEvent event = new BussEvent(BussEvent.Product0);
                    productDetail.setColor(valueBean.getValue());
                    event.setMessage(productDetail);
                    EventBus.getDefault().post(event);
                    MyApplication.getInstance().manager.onBackPressed();
                }
            }
        });
        contentView.findViewById(R.id.popDel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        ((SimpleDraweeView) contentView.findViewById(R.id.popImg)).setImageURI(productDetail.getPicture());
        ((TextView) contentView.findViewById(R.id.popName)).setText(productDetail.getName());
        ((TextView) contentView.findViewById(R.id.popPrice)).setText("￥" + productDetail.getPrice());

        final TagAdapter tagAdapter = new TagAdapter(getActivity());
        popFlowLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);
        popFlowLayout.setAdapter(tagAdapter);
        tagAdapter.clearAndAddAll(datas);
        Tools.showDialog(getActivity());
        NetUtils.getInstance().productAttribute(id, new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                datas.clear();
                String[] split = response.split(",");
                for (int i = 0; i < split.length; i++) {
                    SelectItem.ValueBean valueBean = new SelectItem.ValueBean();
                    valueBean.setValue(split[i]);
                    valueBean.setId(i);
                    datas.add(valueBean);
                }
                tagAdapter.clearAndAddAll(datas);
                // 设置好参数之后再show
                popupWindow.showAtLocation(rootView, Gravity.RIGHT | Gravity.BOTTOM, 0, 0);//显示位置
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
            }
        }, null);
        tagAdapter.setOnItemClick(new OnItemClick() {
            @Override
            public void onItemClick(int type, Object obj) {
                valueBean = (SelectItem.ValueBean) obj;
                for (int i = 0; i < datas.size(); i++) {
                    SelectItem.ValueBean valueBean_ = datas.get(i);
                    valueBean_.setSelected(false);
                    if (valueBean.getId() == valueBean_.getId()) {
                        valueBean_.setSelected(true);
                    }
                }
                tagAdapter.clearAndAddAll(datas);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

//    @Override
    public void onScrollChange(View view, int x, int y, int oldX, int oldY) {
        if (y <= 0) {  //设置标题的背景颜色
            backImg.setImageResource(R.drawable.all_back);
            lyBack.setVisibility(View.VISIBLE);
            titleTv.setVisibility(View.GONE);
            headView.setBackgroundColor(Color.argb((int) 0, 18, 182, 243));
        } else if (y > 0 && y <= glassWeb.getTop()) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
            backImg.setImageResource(R.drawable.arrow_back);
            lyBack.setVisibility(View.GONE);
            titleTv.setVisibility(View.GONE);
            float scale = (float) y / glassWeb.getTop();
            float alpha = (255 * scale);
            headView.setBackgroundColor(Color.argb((int) alpha, 18, 182, 243));
        } else {  //滑动到banner下面设置普通颜色
            backImg.setImageResource(R.drawable.arrow_back);
            titleTv.setVisibility(View.VISIBLE);
            lyBack.setVisibility(View.GONE);
//            headView.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
        }
    }

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y <= 0) {  //设置标题的背景颜色
            backImg.setImageResource(R.drawable.all_back);
            lyBack.setVisibility(View.VISIBLE);
            titleTv.setVisibility(View.GONE);
            headView.setBackgroundColor(Color.argb((int) 0, 18, 182, 243));
        } else if (y > 0 && y <= glassWeb.getTop()) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
            backImg.setImageResource(R.drawable.arrow_back);
            lyBack.setVisibility(View.GONE);
            titleTv.setVisibility(View.GONE);
            float scale = (float) y / glassWeb.getTop();
            float alpha = (255 * scale);
            headView.setBackgroundColor(Color.argb((int) alpha, 18, 182, 243));
        } else {  //滑动到banner下面设置普通颜色
            backImg.setImageResource(R.drawable.arrow_back);
            titleTv.setVisibility(View.VISIBLE);
            lyBack.setVisibility(View.GONE);
//            headView.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
        }
    }
}
